package com.link510.aitools.framework.adapter;


import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.link510.aitools.R;
import com.link510.aitools.core.domain.ActionInfo;

import java.util.List;

public abstract class HomeActionAdapter extends BaseAdapter {

    private static final String TAG = "HomeActionAdapter";


    private LayoutInflater mInflator;

    private Context mContext = null;

    public HomeActionAdapter(Context mContext) {
        this.mContext = mContext;
        mInflator = LayoutInflater.from(mContext);
    }

    /**
     * 调用列表
     *
     * @return List<ActionInfo>
     */
    public abstract List<ActionInfo> getActionInfoList();

    /**
     * 处理方法
     *
     * @param actionInfo 动作
     */
    public abstract void toAction(ActionInfo actionInfo);

    @Override
    public int getCount() {
        return getActionInfoList().size();
    }

    @Override
    public Object getItem(int position) {
        return getActionInfoList().get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("InflateParams")
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        final ActionInfo actionInfo = getActionInfoList().get(i);

        if (actionInfo == null) {
            return view;
        }

        ViewHolder viewHolder = null;
        // General ListView optimization code.
        if (view == null) {
            view = mInflator.inflate(R.layout.item_action, null);
            viewHolder = new ViewHolder();
            viewHolder.actionIcon = (ImageView) view.findViewById(R.id.action_icon);
            viewHolder.actionTitle = (TextView) view.findViewById(R.id.action_title);

            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }


        Glide.with(mContext).load(actionInfo.getIcon()).into(viewHolder.actionIcon);
        viewHolder.actionTitle.setText(actionInfo.getTitle());

        view.setOnClickListener(view1 -> {
            toAction(actionInfo);
            Log.i(TAG, "onClick: " + actionInfo.toString());
        });

        return view;
    }

    static class ViewHolder {
        ImageView actionIcon;
        TextView actionTitle;
    }
}
